﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using XYAC.Framework.MonitorTireMaterialManual.Extensions;
using XYAC.Framework.MonitorTireMaterialManual.IServices;
using XYAC.Framework.MonitorTireMaterialManual.LocalData.Context;
using XYAC.Framework.MonitorTireMaterialManual.LocalData.Models;
using XYAC.Framework.MonitorTireMaterialManual.OracleRemoteDB;

namespace XYAC.Framework.MonitorTireMaterialManual.Services
{
    internal class HyperDbService : ServiceBase<int, LocalDataContext>, IHyperDbService
    {

        private const string __REMOTE_SYNC_STATE_PENDING = "PENDING";
        private const string __REMOTE_SYNC_STATE_COMPLETE = "COMPLETE";

        public HyperDbService(IOptionsMonitor<AppConfig> appConfig, ILogger<HyperDbService> logger, IServiceProvider provider) : base(appConfig, logger, provider)
        {
            //this.LocalDb = provider.GetService<LocalDataContext>();
            //this.MesDb = provider.GetService<OracleMesContext>();
            this.Logger = logger;
        }

        //public LocalDataContext LocalDb { get; }
        //public OracleMesContext MesDb { get; }
        public ILogger Logger { get; }

        /// <summary>
        /// 将中间表数据同步到远程服务器,并且将数据状态更新为Pending
        /// 
        /// 把数据同步到本地条码表库，并更新中间表状态为Complete。
        /// </summary>
        /// <param name="inspectList">来自中间表的条码数据集</param>
        /// <returns></returns>
        public int SyncInspectData(IEnumerable<OracleRemoteDB.YB_LOT_INSPECT> inspectList)
        {
            using (var scope = Provider.CreateScope())
            {
                var LocalDb = scope.ServiceProvider.GetService<LocalDataContext>();
                var MesDb = scope.ServiceProvider.GetService<OracleMesContext>();

                var ret = 0;
                //更改状态为 Complete:
                foreach (var inspect in inspectList)
                {
                    inspect.RECEIVE_FLAG = __REMOTE_SYNC_STATE_COMPLETE;
                    inspect.RECEIVE_DATE=DateTime.Now;
                }
                using (var localTrans = LocalDb.Database.BeginTransaction())
                {
                    using (var remoteTrans = MesDb.Database.BeginTransaction())
                    {
                        try
                        {
                            var lST = inspectList.Select(T => new YB_LOT_INSPECT_Local(T)).ToList();
                            //增加删除逻辑：如果本地已存在，则删除后再添加
                            //var sss=lST.Except( LocalDb.YB_LOT_INSPECT.ToList());
                            //LocalDb.YB_LOT_INSPECT.RemoveRange(sss);
                            //LocalDb.SaveChanges();

                            LocalDb.YB_LOT_INSPECT.AddRange(lST);
                            MesDb.YB_LOT_INSPECT.UpdateRange(inspectList);
                            var mesUpdateRet = MesDb.SaveChanges();
                            var localInsertRet = LocalDb.SaveChanges();
                            if (mesUpdateRet == localInsertRet)
                            {
                                localTrans.Commit();
                                remoteTrans.Commit();
                                ret = mesUpdateRet;
                            }
                            else
                            {
                                localTrans.Rollback();
                                remoteTrans.Rollback();
                            }
                        }
                        catch (Exception ex)
                        {

                            localTrans.Rollback();
                            remoteTrans.Rollback();
                            Logger.LogError("同步中间表条码数据失败!"+ex.Message, ex);
                        }
                    }
                }
                return ret;

            }
        }
    }
}
